package com.yanqu.road.server.cmd.kuang;

import com.yanqu.road.entity.enums.kuang.eKuangAttributeType;
import com.yanqu.road.entity.kuang.KuangConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.kuang.Kuang;
import com.yanqu.road.server.cmd.CrossAppointCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.kuang.CrossKuangMgr;
import com.yanqu.road.server.manager.kuang.activity.CrossKuangActivity;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = CrossProtocol.C_CROSS_KUANG_ENTER_BATTLE, desc = "进入pvp活动")
public class CrossKuangEnterBattleCmd extends CrossAppointCommand {

    private int groupId;

    private Map<eKuangAttributeType, Long> attributeMap = new ConcurrentHashMap<>();

    private long userId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        Kuang.CrossKuangBattleEnterReqMsg reqMsg = Kuang.CrossKuangBattleEnterReqMsg.parseFrom(packet.getBytes());
        groupId = reqMsg.getGroupId();
        for (Kuang.AttributeDataTemp attributeDataTemp : reqMsg.getAttributeList()) {
            eKuangAttributeType type = com.yanqu.road.entity.enums.kuang.eKuangAttributeType.forValue(attributeDataTemp.getType().getNumber());
            if (type == null) {
                continue;
            }
            attributeMap.put(type, attributeMap.getOrDefault(type, 0L) + attributeDataTemp.getValue());
        }
        userId = packet.getPlayerId();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        CrossKuangActivity activity = CrossKuangMgr.getActivity(groupId);
        if (activity == null) {
            ret = GameErrorCode.E_KUANG_BATTLE_ACTIVITY_NOT_FOUND;
            return;
        }
        KuangConfig config = activity.getConfig();
        if (config == null) {
            ret = GameErrorCode.E_KUANG_CONFIG_NOT_FOUND;
            return;
        }
        if (!activity.isOpenTime()) {
            ret = GameErrorCode.E_KUANG_BATTLE_NOT_OPEN;
            return;
        }
        // 先刷下属性
        activity.uploadAttribute(userId, attributeMap);
        // 进入战斗
        ret = activity.enterBattleByCmd(userId);
    }

    @Override
    public void sendData() {
        if (ret != 0) {
            Kuang.KuangBattleEnterRespMsg.Builder respMsg = Kuang.KuangBattleEnterRespMsg.newBuilder();
            respMsg.setRet(ret);
            MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_KUANG_ENTER_BATTLE, respMsg));
        }
    }
}
